#!/usr/bin/env bash
# Summary: Display prefix for a Go version
# Usage: goenv prefix [<version>]
#
# Displays the directory where a Go version is installed.
# If no <version> is given, displays the location of the currently selected version.
# <version> `latest` is given, displays the latest installed version (1.23.4).
# <version> `system` displays the system Go location if installed.
# <version> `1` displays the latest installed major version (1.23.4).
# <version> `23` or `1.23` displays the latest installed minor version (1.23.4).
# <version> `1.23.4` displays this installed version (1.23.4).
# If no version can be found or no versions are installed, an error message will be displayed.
# Run `goenv versions` for a list of available Go versions.

set -e
[ -n "$GOENV_DEBUG" ] && set -x

# Provide goenv completions
if [ "$1" = "--complete" ]; then
  echo latest
  echo system
  exec goenv-versions --bare
fi

versions() {
  # Sort correctly (1.20.9 comes before 1.20.10)
  local query="$1"
  goenv versions --bare | sort -V | $(type -p ggrep grep | head -1) -F "$query" || true
}

latest_version() {
  versions | grep -oE "^$1\\.([0-9]+)?$" | tail -1
}

if [ -n "$1" ]; then
  OLDIFS="$IFS"
  {
    IFS=:
    export GOENV_VERSION="$*"
  }
  IFS="$OLDIFS"
elif [ -z "$GOENV_VERSION" ]; then
  GOENV_VERSION="$(goenv-version-name)"
fi

GOENV_PREFIX_PATHS=()
OLDIFS="$IFS"
{
  IFS=:
  for version in ${GOENV_VERSION}; do
    if [ "$version" = "system" ]; then
      if GO_PATH="$(GOENV_VERSION="${version}" goenv-which go 2>/dev/null)"; then
        GOENV_PREFIX_PATH="${GO_PATH%/bin/*}"
      else
        echo "goenv: system version not found in PATH" >&2
        exit 1
      fi
    else
      if ! LATEST_PATCH="$(goenv-installed "$version" 2>&1)"; then
        echo "goenv: version '${version}' not installed" >&2
        exit 1
      fi
      GOENV_PREFIX_PATH="${GOENV_ROOT}/versions/$LATEST_PATCH"
    fi
    GOENV_PREFIX_PATHS=("${GOENV_PREFIX_PATHS[@]}" "$GOENV_PREFIX_PATH")
  done
}
IFS="$OLDIFS"

OLDIFS="$IFS"
{
  IFS=:
  echo "${GOENV_PREFIX_PATHS[*]}"
}
IFS="$OLDIFS"
